package code.example.base.data.struct.stack;

import code.example.tool.LogFactory;

import java.util.Arrays;
import java.util.EmptyStackException;

public class MyStack {
    Object [] items  =null;
    int top = -1;
    public MyStack(int capacity){
        items =new Object[capacity];
    }
    public void push(Object object){
        int newTop = ++ this.top ;
        int length = items.length;
        if(newTop == length){
            grow();
        }
        items[newTop] = object;
    }

    private void grow(){
        int oldLength = items.length;
        Object [] newItems = new Object [oldLength*2];
        System.arraycopy(items,0,newItems,0,oldLength);
        this.items =  newItems;
    }
    public Object  pop(){
        int top = this.top;
        if(top == -1){
            throw new EmptyStackException();
        }

        Object obj = this.items[top];
        this.items[top] = null;
        this.top --;
        return obj;
    }




    @Override
    public String toString() {
        return "MyStack{" +
                "items=" + Arrays.toString(items) +
                ", top=" + top +
                '}';
    }

    public static void main(String [] args ){
        MyStack myStack= new MyStack(3);
        String str ="";
        for(int i=0;i<1000;i++){
            String element  =  str+i;
            myStack.push(element);
        }
        LogFactory.getLog().info(myStack.toString());
        StringBuilder sb = new StringBuilder();
        for(int i=0;i<1000;i++){
            String element  =  (String)myStack.pop();
            sb.append(element).append(", ");
        }
        LogFactory.getLog().info(sb.toString());
    }
}
